package com.darren.befriend.fragments;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Dialog;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.darren.befriend.HomeActivity;
import com.darren.befriend.R;
import com.darren.befriend.adapters.FriendsAdapter;
import com.darren.befriend.adapters.FriendsAdapter.OpenItemListener;
import com.darren.befriend.adapters.FriendsAdapter.onDeleteListener;
import com.darren.befriend.utilities.LogUtil;
import com.darren.befriend.views.MyProgressDialog;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;

public class FriendsFragment extends Fragment {

	private static FriendsFragment mInstance;
	private ParseUser mCurrentUsr;
	private ListView mFriendListview;
	public static ArrayList<ParseUser> mFriendList;
	public static boolean needToReloadList = true;
	public static ArrayList<ParseObject> requestArray;
	private ArrayList<String> sentRequests;
	private FriendsAdapter mFriendAdapter;
	private onDeleteListener mDeleteLister;
	private OpenItemListener mOpenListener;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	public static FriendsFragment makeInstance() {
		if (mInstance == null) {

			mInstance = new FriendsFragment();
		}

		return mInstance;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		ViewGroup view = (ViewGroup) inflater.inflate(R.layout.layout_friends,
				container, false);
		final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) view
				.findViewById(R.id.swipe);
		swipeView.setColorScheme(R.color.white, R.color.white, R.color.white,
				R.color.white);
		swipeView
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
					@Override
					public void onRefresh() {

						swipeView.setRefreshing(true);
						new LoadFriendsAsync().execute();
					}
				});
		mFriendListview = (ListView) view.findViewById(R.id.friends_list);
		mDeleteLister = new onDeleteListener() {

			@Override
			public void onDelete(int position) {
				// TODO Auto-generated method stub
				deleteFriend(position);
			}
		};

		mOpenListener = new OpenItemListener() {

			@Override
			public void onOpen(int position) {
				// TODO Auto-generated method stub

				if (position < requestArray.size()) {

					gotoChat(mFriendList.get(position), true,
							requestArray.get(position));
				} else {

					gotoChat(mFriendList.get(position), false, null);
				}
			}
		};
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (getActivity() instanceof HomeActivity) {

			((HomeActivity) getActivity())
					.setRightImage(R.drawable.icon_search);
			((HomeActivity) getActivity()).setLeftImage(R.drawable.icon_menu);
			((HomeActivity) getActivity()).setActivityTitle("Friends");
			((HomeActivity) getActivity()).showRightButtonImg(false);
			mCurrentUsr = ((HomeActivity) getActivity()).getCurrentUser();
			if (needToReloadList) {

				new LoadFriendsAsync().execute();
			} else {

				loadViews();
			}
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	private void gotoChat(ParseUser user, boolean isRequest,
			ParseObject requestObject) {

		if (getActivity() instanceof HomeActivity) {
			if (isRequest) {

				UserInfoDetailFragment fragment = UserInfoDetailFragment
						.makeInstance(user, false, true, requestObject);
				HomeActivity activity = (HomeActivity) getActivity();
				activity.switchContentWithNormalAnimation(fragment);
			} else {

				ChatFragment fragment = ChatFragment.makeInstance(user);
				HomeActivity act = (HomeActivity) getActivity();
				act.switchContentWithNormalAnimation(fragment);
			}
		}
	}

	/**
	 * loadViews
	 */
	private void loadViews() {

		Display display = getActivity().getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		mFriendAdapter = new FriendsAdapter(getActivity(), mFriendList,
				sentRequests, requestArray, size.x);
		mFriendListview.setAdapter(mFriendAdapter);
		mFriendAdapter.setDeleteListener(mDeleteLister);
		mFriendAdapter.setOpenListener(mOpenListener);
	}

	@SuppressWarnings("unchecked")
	private void deleteFriend(int index) {
		ParseUser friend = mFriendList.get(index);
		ArrayList<String> friends = (ArrayList<String>) mCurrentUsr
				.get("Friends");
		ArrayList<String> newFriends = new ArrayList<String>();
		for (String friendname : friends) {
			if (friendname.equals(friend.getUsername())) {

				continue;
			}

			newFriends.add(friendname);
		}

		mCurrentUsr.put("Friends", newFriends);
		ArrayList<String> array = (ArrayList<String>) mCurrentUsr.get("Enemy");
		boolean isFound = false;
		for (String element : array) {
			String[] usr = element.split("\\$\\$\\$");
			if (friend.getUsername().equals(usr[0])) {

				isFound = true;
			}
		}

		if (!isFound) {

			int currentTime = (int) new Date().getTime() / 1000;
			String object = String.format("%s$$$%d", friend.getUsername(),
					currentTime);
			array.add(object);
		}

		mCurrentUsr.put("Enemy", array);
		mFriendList.remove(index);
		mFriendAdapter.notifyDataSetChanged();
		mCurrentUsr.saveInBackground();
	}

	private class LoadFriendsAsync extends AsyncTask<Void, Void, Void> {

		private Dialog dialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = MyProgressDialog.show(getActivity(), "", "", false, false);
		}

		@SuppressWarnings("unchecked")
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			mFriendList = new ArrayList<ParseUser>();
			requestArray = new ArrayList<ParseObject>();
			sentRequests = new ArrayList<String>();
			ParseQuery<ParseObject> queryRequest = ParseQuery
					.getQuery("Requests");
			try {
				ArrayList<Boolean> values = new ArrayList<Boolean>();
				ArrayList<String> users = new ArrayList<String>();
				values.add(false);
				users.add(mCurrentUsr.getUsername());

				// Receiver
				queryRequest.setLimit(1000);
				queryRequest.whereContainedIn("Resolve", values);
				queryRequest.whereContainedIn("Receiver", users);
				List<ParseObject> result = new ArrayList<ParseObject>();
				List<ParseObject> receiver = queryRequest.find();
				if (receiver != null) {

					result.addAll(receiver);
				}

				// Sender
				queryRequest = ParseQuery.getQuery("Requests");
				queryRequest.setLimit(1000);
				queryRequest.whereContainedIn("Resolve", values);
				queryRequest.whereContainedIn("Sender", users);
				List<ParseObject> sender = queryRequest.find();
				if (sender != null) {

					result.addAll(sender);
				}

				for (ParseObject element : result) {

					if (element.get("Sender").equals(mCurrentUsr.getUsername())) {

						sentRequests.add((String) element.get("Receiver"));
					}

					if (!element.get("Receiver").equals(
							mCurrentUsr.getUsername())) {

						continue;
					}

					requestArray.add((ParseObject) element);
					ParseQuery<ParseUser> query = ParseUser.getQuery();
					ArrayList<String> queryUser = new ArrayList<String>();
					queryUser.add((String) element.get("Sender"));
					query.whereContainedIn("username", queryUser);
					try {

						List<ParseUser> requests = query.find();
						if (requests != null) {

							for (int i = 0; i < requests.size(); i++) {

								mFriendList.add(requests.get(0));
							}
						}
					} catch (ParseException e) {

					}
				}

				ArrayList<ParseUser> friends = new ArrayList<ParseUser>();
				if (mCurrentUsr.get("Friends") == null) {

					return null;
				}

				friends = (ArrayList<ParseUser>) mCurrentUsr.get("Friends");
				ParseQuery<ParseUser> query = ParseUser.getQuery();
				query.whereContainedIn("username", friends);
				List<ParseUser> user = query.find();
				if (user != null) {

					mFriendList.addAll(user);
				}

				for (ParseUser friend : mFriendList) {
					try {

						friend.fetch();
					} catch (ParseException e) {

						e.printStackTrace();
					}
				}
			} catch (Exception ex) {

				LogUtil.e("Load friends", "Fails");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			try {

				loadViews();
				dialog.dismiss();
			} catch (Exception ex) {

				LogUtil.e("Dismis dialog", ex.getMessage());
			}
		}
	}
}
